<?php

namespace app\command;

use app\model\Order;
use app\model\OrderFlow;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use Wechat\CommerceApp;

class FlowTaskCommand extends Command
{
    protected function configure()
    {
        $this->setName('flow')
            ->setDescription('获取流水明细信息');
    }

    protected function execute(Input $input, Output $output)
    {
        $next_key   = '';
        $page       = 1;
        $date       = date('Y-m-d', strtotime('-1 day', time()));
        $start_time = strtotime($date);
        $end_time   = strtotime($date . ' 23:59:59');

        do {
            [$list, $next_key, $has_more] = CommerceApp::getInstance()->getFlowList($page, $next_key, $start_time, $end_time);
            $next_key = $next_key ?? '';
            $has_more = $has_more ?? false;
            $page++;

            if ($list) {
                $save = [];
                foreach ($list as $item) {
                    try {
                        $info  = CommerceApp::getInstance()->getFlowInfo($item);
                        $order = Order::where('order_id', $info['order_id'])->value('id');
                        if ($order) {
                            $save[] = [
                                'flow_id'          => $item,
                                'order_id'         => $info['order_id'],
                                'amount'           => $info['amount'],
                                'bookkeeping_time' => $info['bookkeeping_time'],
                                'remark'           => $info['remark'],
                            ];
                        }
                    } catch (\Exception $e) {
                        continue;
                    }
                }
                if ($save) {
                    (new OrderFlow())->saveAll($save);
                }
            }
        } while ($has_more);
    }
}
